// utils/network.js - 网络状态和错误处理工具
const app = getApp()

/**
 * 检查网络状态
 */
function checkNetworkStatus() {
  return new Promise((resolve, reject) => {
    wx.getNetworkType({
      success: (res) => {
        const networkType = res.networkType
        if (networkType === 'none') {
          reject(new Error('网络连接不可用'))
        } else {
          resolve(networkType)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * 显示网络错误提示
 */
function showNetworkError() {
  wx.showModal({
    title: '网络错误',
    content: '请检查网络连接后重试',
    showCancel: false,
    confirmText: '知道了'
  })
}

/**
 * 显示服务器错误提示
 */
function showServerError(message = '服务器繁忙，请稍后重试') {
  wx.showModal({
    title: '服务异常',
    content: message,
    showCancel: false,
    confirmText: '知道了'
  })
}

/**
 * 统一错误处理
 */
function handleError(error, showToast = true) {
  console.error('Error:', error)
  
  if (showToast) {
    if (error.message && error.message.includes('网络')) {
      showNetworkError()
    } else if (error.message && error.message.includes('服务器')) {
      showServerError(error.message)
    } else {
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none',
        duration: 2000
      })
    }
  }
  
  return error
}

/**
 * 重试机制的请求
 */
function requestWithRetry(options, maxRetries = 3) {
  return new Promise((resolve, reject) => {
    let retryCount = 0
    
    function makeRequest() {
      wx.request({
        ...options,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res)
          } else if (res.statusCode >= 500 && retryCount < maxRetries) {
            retryCount++
            setTimeout(makeRequest, 1000 * retryCount) // 递增延迟重试
          } else {
            reject(new Error(`HTTP ${res.statusCode}`))
          }
        },
        fail: (err) => {
          if (retryCount < maxRetries) {
            retryCount++
            setTimeout(makeRequest, 1000 * retryCount)
          } else {
            reject(err)
          }
        }
      })
    }
    
    makeRequest()
  })
}

/**
 * 检查服务器连通性
 */
function checkServerConnection() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.baseUrl}/health`, // 假设有健康检查接口
      method: 'GET',
      timeout: 5000,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(true)
        } else {
          reject(new Error('服务器连接异常'))
        }
      },
      fail: (err) => {
        reject(new Error('无法连接到服务器'))
      }
    })
  })
}

/**
 * 网络状态监听
 */
function startNetworkMonitoring() {
  wx.onNetworkStatusChange((res) => {
    if (!res.isConnected) {
      wx.showToast({
        title: '网络连接已断开',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.showToast({
        title: '网络连接已恢复',
        icon: 'success',
        duration: 1500
      })
    }
  })
}

/**
 * 停止网络状态监听
 */
function stopNetworkMonitoring() {
  wx.offNetworkStatusChange()
}

module.exports = {
  checkNetworkStatus,
  showNetworkError,
  showServerError,
  handleError,
  requestWithRetry,
  checkServerConnection,
  startNetworkMonitoring,
  stopNetworkMonitoring
}
